package com.jdbc.util;

import com.bean.Course;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;

public class DBUtilForTeacher {
	Connection conn = null;
	Statement stat = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	int successful = -1;

	/**
	 * get connection
	 */
	public Connection getConn() {
		try {
			Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
			conn =
					DriverManager.getConnection(
							"jdbc:mysql://www.xiaotao2333.top:3306/selectCourse", "xiaotao", "mojintao233");
		} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return conn;
	}

	/**
	 * close connection and release
	 */
	public void release() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (stat != null) {
				stat.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public int insert(String sql, Course c) {
		if (conn == null) {
			conn = this.getConn();
		}

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, c.getCourseId());
			ps.setString(2, c.getCourseName());
			ps.setString(3, c.getTeacher());
			ps.setLong(4, c.getPoint());
			ps.setString(5, c.getTime1());
			ps.setString(6, c.getTime2());
			ps.setString(7, c.getLocation());
			ps.setLong(8, c.getLimited());

			successful = ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return successful;
	}

	/**
	 * query
	 */
	public ResultSet getResult(String sql, String[] args) {
		rs = null;

		if (conn == null) {
			conn = this.getConn();
		}

		try {
			ps = conn.prepareStatement(sql);

			for (int i = 0; i < args.length; i++) {
				ps.setString(i + 1, args[i]);
			}

			rs = ps.executeQuery();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return rs;
	}

	public ResultSet getResult(String sql) {
		rs = null;

		if (conn == null) {
			conn = this.getConn();
		}

		try {
			stat = conn.createStatement();
			rs = stat.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return rs;
	}
}
